<?php
/**
 * Function:
 * Description:
 * Abo 2019/6/4 11:44
 * Email: abo2013@foxmail.com
 */

namespace Abo\Fasterapi\Console;


class CommandInstallLogic
{
    const FASTER_ROUTER_FUNCTION_USE = '        $this->mapFasterapiRoutes();';
    const FASTER_ROUTER_FUNCTION = "
            protected function mapFasterapiRoutes()
    {
        Route::prefix('fasterapi')
            ->middleware( 'api' )
            ->namespace(".'$this->namespace'." . '\Fasterapi')
            ->group(base_path('routes/fasterapi.php'));
    }
        ";

    const MAP_FUNCTION = "public function map()
    {";

    /** 添加Api路由 string $inputClassName : trim( $this->argument( 'name' ) ) */
    public function addFastapiRoute( string $inputClassName )
    {
        list( $className2Route, $className ) = $this->getControllerName( $inputClassName );
        $defaultRoute = "\r
Route::resource('{$className2Route}', '{$className}');\r
        ";

        $routePath = base_path( 'routes/fasterapi.php' );
        if ( !file_exists( $routePath ) ) {
            $defaultRoute = "<?php\r\n".$defaultRoute;
        }

        file_put_contents( $routePath, $defaultRoute, FILE_APPEND );
    }

    /** 设置路由服务 */
    public function setRouteServiceProvider()
    {
        $copyTargetRoutePath = base_path('routes/fasterapi.php');
        $copyTargetProviderPath = app_path( 'Providers/RouteServiceProvider.php' );

        // 路由提供者 注册 Fastapi
        if ( !file_exists( $copyTargetProviderPath ) ) {
            copy( __DIR__ . '/V0/Routes/RouteServiceProvider.php', $copyTargetProviderPath );
        }else{

            $RouteFileContent = file_get_contents( $copyTargetProviderPath );

            // 写入方法
            if ( !strstr( $RouteFileContent, 'mapFasterapiRoutes' ) ) {
                $RouteFileContent = rtrim( rtrim( $RouteFileContent ), '}' );
                $RouteFileContent .= self::FASTER_ROUTER_FUNCTION."\r\n}";
            }

            // map 写入调用
            $RouteFileContent = str_replace( self::MAP_FUNCTION,
                self::MAP_FUNCTION."\r\n".self::FASTER_ROUTER_FUNCTION_USE,
                $RouteFileContent
            );

            file_put_contents( $copyTargetProviderPath, $RouteFileContent, FILE_BINARY );
        }

        // 路由文件复制
        if ( !file_exists( $copyTargetRoutePath ) ) {
            copy( __DIR__ . '/../V0/Routes/fasterapi.php', $copyTargetRoutePath );
        }
    }

    /** 获取输入类名 */
    protected function getControllerName( string $inputClassName )
    {
        // $inputClassName = trim( $this->argument( 'name' ) );
        if ( !strstr( $inputClassName, 'Controller' ) ) {
            throw new \Exception( 'ClassName does not vaild !' );
        }

        $className = strtolower( preg_replace( '/([a-z])([A-Z])/', "$1" . '_' . "$2", $inputClassName ) );
        return [ str_replace( '_controller', '', $className ), $inputClassName ];
    }
}